package com.ruyuan.seckilling.purchase.async;

import com.ruyuan.starter.async.AsyncContext;
import com.ruyuan.starter.async.BossEventBus;
import com.ruyuan.starter.async.event.BaseEvent;
import com.ruyuan.starter.async.listener.EventListener;
import com.ruyuan.starter.async.thread.ExecutorService;
import com.ruyuan.starter.jedis.CacheSupport;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * @author zhonghuashishan
 */
public abstract class BasePurchaseListener<E extends BaseEvent> implements EventListener<BaseEvent> {

    @Autowired
    protected BossEventBus bossEventBus;

    @Autowired
    protected ExecutorService executorService;

    @Autowired
    protected CacheSupport cacheSupport;

    @Override
    public void onEvent(BaseEvent event, AsyncContext eventContext) {
        PurchaseContext purchaseContext = (PurchaseContext) eventContext;
        doThisStep(((E) event), purchaseContext);
    }

    protected abstract void doThisStep(E event, PurchaseContext purchaseContext);

    protected void response(javax.servlet.AsyncContext asyncContext, boolean success, String info) {
        ServletResponse response = asyncContext.getResponse();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        try (ServletOutputStream out = response.getOutputStream()) {
            String s = "{\"success\":"+success+", \"info\":\""+info+"\"}";
            out.write(s.getBytes(StandardCharsets.UTF_8));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            asyncContext.complete();
        }
    }
}
